<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('39.108.170.27', 5672, 'guest', 'guest');
//打开一个连接和一个通道
$channel = $connection->channel();

//声明我们将要消耗的队列
$channel->queue_declare('task_queue456', false, true, false, false);

echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

$callback = function($msg){
    echo " [x] Received ", $msg->body, "\n";
    file_put_contents("/www/wwwroot/rabbitmq_test/test.log", $msg->body.'--'.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND);
    echo " [x] Done", "\n";
    $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
};

#翻译时注：只有consumer已经处理并确认了上一条message时queue才分派新的message给它
$channel->basic_qos(null, 1, null);
$channel->basic_consume('task_queue456', '', false, true, false, false, $callback);

/* $i = 0;
while (true) {
    $i++;
    file_put_contents("/www/wwwroot/rabbitmq_test/test.log","'@@@-{$i}-".date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND);
    while(count($channel->callbacks)) {
        $channel->wait();
    }
    usleep(500);
} */
//$channel->close();
//$connection->close();

try {
    //监听数据
    while (count($channel->callbacks)) {
        $channel->wait();
    }
} catch (\PhpAmqpLib\Exception\AMQPTimeoutException $e) {
    echo $e->getMessage();
    file_put_contents("/www/wwwroot/rabbitmq_test/time_out.log", $e->getMessage().'--'.date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND);
    $channel->close();
    $connection->close();
}
